//
//  classifyViewController.m
//  LazyCat
//
//  Created by rocky on 15/12/30.
//  Copyright (c) 2015年 zhanshu. All rights reserved.
//

#import "classifyViewController.h"
#import "FeWifiManHub.h"
#import "addViewController.h"
#import "ClassifyManageViewController.h"
#import "AFNetworkHandler.h"
#import "classifyTableViewCell.h"
    
@interface classifyViewController ()<UITableViewDataSource,UITableViewDelegate,addBackdelegate,successEditDelegate>
{
    FeWifiManHub *_loading;
}
@property (nonatomic,strong) UITableView *tableV;//表视图
@property (nonatomic,strong) NSMutableArray *dataArr;//获取数组数组
@property (nonatomic,strong) NSMutableArray *headerArr;//头部显隐数组
@property (nonatomic,strong) UIView *noNetView;//无网络视图
@property (nonatomic,strong) UIView *noDataView;//无数据视图
@property (nonatomic,strong) UIView *btnView;//下面按钮视图

@end

@implementation classifyViewController
-(void)successEditStr:(NSString *)str {//代理用于刷新页面
    if ([str isEqualToString:@"T"]) {
        [self getData];
    }
}
-(void)AddValue:(NSString *)val {//代理用于刷新页面
    if ([val isEqualToString:@"m"]) {
        [self getData];
    }
}
-(void)viewWillAppear:(BOOL)animated {
    if (kNetworkNotReachability) {
        [[MessShowView share] showWithMess:@"当前网络不给力"];
        self.noNetView.hidden = NO;
        self.tableV.hidden = YES;
        [_loading dismiss];
        [_loading removeFromSuperview];
    }else {
        self.tableV.hidden = NO;
        self.noNetView.hidden = YES;
    }
}
- (void)viewDidLoad {
    [super viewDidLoad];
    [self initNav:@"选择分类" doBack:YES];
    UIView *lineV = [[UIView alloc]initWithFrame:CGRectMake(0, 63, ScreenWidth, 1)];
    lineV.alpha = 0.2;
    lineV.backgroundColor = [UIColor lightGrayColor];
    [self.navBar addSubview:lineV];
    [self createTableV];//创建表视图
    [self getData];//获取数据
}
-(void)createTableV {//创建表视图
    //第一块表视图
    self.tableV = [[UITableView alloc]initWithFrame:CGRectMake(0, 64, ScreenWidth, ScreenHeight-104) style:UITableViewStyleGrouped];
    self.tableV.backgroundColor = BackColor;
    self.tableV.delegate = self;
    self.tableV.dataSource = self;
    [self.view addSubview:self.tableV];
    self.tableV.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.tableV registerClass:[classifyTableViewCell class] forCellReuseIdentifier:@"Cell"];//注册
    //第二块加载视图
    _loading = [[FeWifiManHub alloc] initWithView:self.view withMode:FeWifiManHubModeOnlyLoader];
    [self.view addSubview:_loading];
    [_loading show];
    //第三块无网络视图
    self.noNetView = [[UIView alloc] initWithFrame:CGRectMake(0, 64, ScreenWidth, ScreenHeight - 104)];
    self.noNetView.hidden = YES;
    self.noNetView.backgroundColor = [UIColor colorWithRed:242 / 255.0 green:243 / 255.0 blue:247 / 255.0 alpha:1];
    [self.view addSubview:self.noNetView];
    UIImageView *netImg = [[UIImageView alloc] initWithFrame:CGRectMake((ScreenWidth-100)/2, 60, 100, 90)];
    netImg.image = [UIImage imageNamed:@"无网络_r1_c1"];
    [self.noNetView addSubview:netImg];
    UILabel *netFail = [[UILabel alloc] initWithFrame:CGRectMake(0, 170, ScreenWidth, 20)];
    netFail.text = @"网络请求失败";
    netFail.textAlignment = NSTextAlignmentCenter;
    netFail.font = [UIFont systemFontOfSize:16];
    [self.noNetView addSubview:netFail];
    UIButton *refresh = [[UIButton alloc] initWithFrame:CGRectMake((ScreenWidth-120)/2, 200, 120, 40)];
    [refresh setImage:[UIImage imageNamed:@"无网络_r3_c2 下午4.23.04"] forState:UIControlStateNormal];
    refresh.adjustsImageWhenHighlighted = NO;
    [self.noNetView addSubview:refresh];
    [refresh addTarget:self action:@selector(refreshV) forControlEvents:UIControlEventTouchUpInside];//刷新
    //第四块无数据视图
    self.noDataView = [[UIView alloc]initWithFrame:CGRectMake(0, 64, ScreenWidth, ScreenHeight-104)];
    self.noDataView.hidden = YES;
    self.noDataView.backgroundColor = BackColor;
    [self.view addSubview:self.noDataView];
    UIImageView *noDataIV = [[UIImageView alloc]initWithFrame:CGRectMake((ScreenWidth-80)/2, 70, 80, 80)];
    noDataIV.image = [UIImage imageNamed:@"wufenlei"];
    [self.noDataView addSubview:noDataIV];
    UILabel *nodataL = [[UILabel alloc]initWithFrame:CGRectMake(0, 165, ScreenWidth, 25)];
    nodataL.text = @"抱歉,您暂时还没有分类";
    nodataL.textAlignment = NSTextAlignmentCenter;
    nodataL.font = [UIFont systemFontOfSize:16];
    nodataL.textColor = [UIColor lightGrayColor];
    [self.noDataView addSubview:nodataL];
    self.btnView = [[UIView alloc]initWithFrame:CGRectMake(0, ScreenHeight-40, ScreenWidth, 40)];
    self.btnView.hidden = YES;
    self.btnView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:self.btnView];
    UIButton *addBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    addBtn.backgroundColor = MainColor;
    addBtn.layer.cornerRadius = 5.0;
    addBtn.layer.masksToBounds = YES;
    addBtn.titleLabel.font = [UIFont systemFontOfSize:16];
    [addBtn setTitle:@"添加分类" forState:UIControlStateNormal];
    [addBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    addBtn.frame = CGRectMake(10, 5, (ScreenWidth-40)/2, 30);
    [self.btnView addSubview:addBtn];
    [addBtn addTarget:self action:@selector(addClassify) forControlEvents:UIControlEventTouchUpInside];//点击新增分类
    UIButton *managerBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    managerBtn.backgroundColor = MainColor;
    managerBtn.layer.cornerRadius = 5.0;
    managerBtn.layer.masksToBounds = YES;
    managerBtn.titleLabel.font = [UIFont systemFontOfSize:16];
    [managerBtn setTitle:@"分类管理" forState:UIControlStateNormal];
    [managerBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    managerBtn.frame = CGRectMake(30+(ScreenWidth-40)/2, 5, (ScreenWidth-40)/2, 30);
    [self.btnView addSubview:managerBtn];
    [managerBtn addTarget:self action:@selector(managerClassify) forControlEvents:UIControlEventTouchUpInside];//点击新增分类
}
-(void)getData {//获取数据
    if (kNetworkNotReachability) {
        [[MessShowView share] showWithMess:@"当前网络不给力"];
        [_loading dismiss];
        [_loading removeFromSuperview];
    }
    NSString *url = [NSString stringWithFormat:classifyUrl,[AppData share].username];
    [AFNetworkHandler GETWithAFNByURL:url completion:^(id result) {
        NSDictionary *dict = result;
        NSString *r = dict[@"r"];
        if ([r isEqualToString:@"T"]) {
            self.dataArr = [NSMutableArray array];
            self.dataArr = dict[@"categories"];
//            self.headerArr = [NSMutableArray array];//头部显隐数组
//            NSMutableArray *topHeaderArr = [NSMutableArray arrayWithArray:[NSUserDefualManager getValueByKey:@"top"]];
//            if (topHeaderArr.count == 0) {
//                for (int i = 0; i < self.dataArr.count; i++) {
//                    [self.headerArr addObject:@"0"];
//                }
//            }else {
//                self.headerArr = [NSMutableArray arrayWithArray:topHeaderArr];
//            }
//            for (int i = 0; i < self.dataArr.count; i++) {//这里是判断哪个地方显示对号
//                NSString *faID = [self.dataArr[i] objectForKey:@"categoryid"];
//                if ([self.nameId isEqualToString:faID]) {
//                    [self.headerArr replaceObjectAtIndex:i withObject:@"1"];
//                }else {
//                    NSArray *arr = [self.dataArr[i] objectForKey:@"childrencategory"];
//                    for (int j = 0; j < arr.count; j++) {
//                        NSString *sonID = [arr[j] objectForKey:@"categoryid"];
//                        if ([self.nameId isEqualToString:sonID]) {
//                            [self.headerArr replaceObjectAtIndex:i withObject:@"1"];
//                        }else {
//                            
//                        }
//                    }
//                }
//            }
            if (self.dataArr.count > 0) {
                self.tableV.hidden = NO;
                self.noDataView.hidden = YES;
                
                [self.tableV reloadData];
            }else {
                self.tableV.hidden = YES;
                self.noDataView.hidden = NO;
            }
            [_loading dismiss];
            [_loading removeFromSuperview];
        }else {
            [_loading dismiss];
            [_loading removeFromSuperview];
        }
    }];
    self.btnView.hidden = NO;
    [_loading dismiss];
    [_loading removeFromSuperview];
}
//uitableViewDatasource
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.dataArr.count;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    NSArray *arr = [self.dataArr[section] objectForKey:@"childrencategory"];
//    NSString *open;
//    if (self.headerArr.count > 0) {
//        open = [NSString stringWithFormat:@"%@",self.headerArr[section]];
//    }else {
//        
//    }
//    BOOL isOpen;
//    if ([open isEqualToString:@"0"]) {
//        isOpen = NO;
//    }else {
//        isOpen = YES;
//    }
//    NSInteger count = isOpen?arr.count:0;
//    return count;
    return arr.count;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    classifyTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell" ];
    cell.editBtn.hidden = YES;
    cell.delateBtn.hidden = YES;
    cell.replaceBtn1.hidden = YES;
    cell.replaceBtn2.hidden = YES;
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    NSArray *arr = [self.dataArr[indexPath.section] objectForKey:@"childrencategory"];
    NSString *secondIsAdvance = [arr[indexPath.row] objectForKey:@"isactived"];//子分类是否启用
    if ([secondIsAdvance isEqualToString:@"0"]) {
        cell.nameL.text = [NSString stringWithFormat:@"%@(未启用)",[arr[indexPath.row] objectForKey:@"categoryname"]];
    }else {
        cell.nameL.text = [NSString stringWithFormat:@"%@",[arr[indexPath.row] objectForKey:@"categoryname"]];
    }
    cell.backgroundColor = [UIColor colorWithRed:248/255.0 green:248/255.0 blue:248/255.0 alpha:1.0];
    if (indexPath.row == arr.count - 1) {
        cell.lineV.frame = CGRectMake(0, 39, ScreenWidth, 1);
    }else {
        cell.lineV.frame = CGRectMake(15, 39, ScreenWidth-15, 1);
    }
    if ([self.nameId isEqualToString:[arr[indexPath.row] objectForKey:@"categoryid"]]) {
        cell.duiIV.hidden = NO;
    }else {
        cell.duiIV.hidden = YES;
    }
    return cell;
}
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {//创建头部视图
    UIView *headerV = [[UIView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, 50)];
    headerV.backgroundColor = [UIColor whiteColor];
    UILabel *classL = [[UILabel alloc]initWithFrame:CGRectMake(10, 0, ScreenWidth-70, 50)];
    classL.textAlignment = NSTextAlignmentLeft;
    classL.font = [UIFont systemFontOfSize:16];
    classL.textColor = [UIColor colorWithRed:51/255.0 green:51/255.0 blue:51/255.0 alpha:1.0];
    NSString *firstIsAdvance = [self.dataArr[section] objectForKey:@"isactived"];//父分类是否启用
    if ([firstIsAdvance isEqualToString:@"0"]) {
        classL.text = [NSString stringWithFormat:@"%@(未启用)",[self.dataArr[section] objectForKey:@"categoryname"]];
    }else {
        classL.text = [NSString stringWithFormat:@"%@",[self.dataArr[section] objectForKey:@"categoryname"]];
    }
    [headerV addSubview:classL];
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
    btn.frame = CGRectMake(0, 0, ScreenWidth, 50);
    btn.tag = section;
    [btn addTarget:self action:@selector(isOpen:) forControlEvents:UIControlEventTouchUpInside];//点击打开单元格
    [headerV addSubview:btn];
    UIView *lineV = [[UIView alloc]initWithFrame:CGRectMake(0, 49, ScreenWidth, 1)];
    lineV.alpha = 0.2;
    lineV.backgroundColor = [UIColor lightGrayColor];
    [headerV addSubview:lineV];
    UIImageView *duiIV = [[UIImageView alloc]initWithFrame:CGRectMake(ScreenWidth-35, 17, 24, 16)];
    [headerV addSubview:duiIV];
    if ([self.nameId isEqualToString:[self.dataArr[section] objectForKey:@"categoryid"]]) {
        duiIV.image = [UIImage imageNamed:@"chanpin_cur"];
        duiIV.hidden = NO;
    }else {
        duiIV.image = [UIImage imageNamed:@""];
        duiIV.hidden = YES;
    }
    return headerV;
}
-(void)isOpen:(UIButton *)btn {//点击打开单元格
    NSLog(@"点击头部");
//    NSString *str = self.headerArr[btn.tag];
//    if ([str isEqualToString:@"0"]) {
//        [self.headerArr replaceObjectAtIndex:btn.tag withObject:@"1"];
//        [NSUserDefualManager storageValue:self.headerArr forKey:@"top"];
//        [self.tableV reloadData];
//    }else {
//        [self.headerArr replaceObjectAtIndex:btn.tag withObject:@"0"];
//        [NSUserDefualManager storageValue:self.headerArr forKey:@"top"];
//        [self.tableV reloadData];
//    }
    NSArray *arr = [self.dataArr[btn.tag] objectForKey:@"childrencategory"];
    if (arr.count > 0) {
        
    }else {
        NSString *mingzi = [self.dataArr[btn.tag] objectForKey:@"categoryname"];
        NSString *biaoshi = [self.dataArr[btn.tag] objectForKey:@"categoryid"];
        [self.delegate backPassName:mingzi nameId:biaoshi];
        [self.navigationController popViewControllerAnimated:YES];
    }
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {//单元格高度
    return 40;
}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {//头部视图高度
    return 50;
}
-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {//尾部视图高度
    return 0.01;
}
-(void)refreshV {//刷新获取数据
    if (kNetworkNotReachability) {
        [[MessShowView share] showWithMess:@"当前网络不给力"];
        self.noNetView.hidden = NO;
        self.tableV.hidden = YES;
    }else {
        self.tableV.hidden = NO;
        self.noNetView.hidden = YES;
        [self getData];//获取数据
    }
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    NSArray *arr = [self.dataArr[indexPath.section] objectForKey:@"childrencategory"];
    NSString *mingzi = [arr[indexPath.row] objectForKey:@"categoryname"];
    NSString *biaoshi = [arr[indexPath.row] objectForKey:@"categoryid"];
    [self.delegate backPassName:mingzi nameId:biaoshi];
    [self.navigationController popViewControllerAnimated:YES];
}
-(void)addClassify {//跳到添加分类页面
    addViewController *addVC = [[addViewController alloc]init];
    addVC.isFrom = @"100";
    addVC.HeadArr = self.dataArr;
    addVC.delegate = self;
    [self.navigationController pushViewController:addVC animated:YES];
}
-(void)managerClassify {//跳到编辑页面
    ClassifyManageViewController *classifyManaVC = [[ClassifyManageViewController alloc]init];
    classifyManaVC.delegate = self;
    [self.navigationController pushViewController:classifyManaVC animated:YES];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}
@end
